package com.training.dao;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

//import org.hibernate.cfg.Configuration;

public class DAO {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		// Close caches and connection pools
		getSessionFactory().close();
	}
	public static <E> E inSession(SessMod<E> mod){
		E rezult = null;
		Transaction tx = null;
		Session session = DAO.getSessionFactory().openSession();
		try{
			tx = session.beginTransaction();
			rezult = mod.action(session);
			tx.commit();
		}catch(Exception ex){
			if (tx != null && tx.isActive()) {
		        try {
					System.out.println("inSession: "+ex);
					System.out.println("Rollback transaction...");
		        	tx.rollback();
		        } catch (HibernateException e1) {
					System.out.println("Error rolling back transaction");
		        }
		        //throw ex;
			}
		}
		session.close();
		return rezult;
	}

	private static final UserDAO user = new UserDAO();
	public static UserDAO getUser() {
		return user;
	}
	private static final RoleDAO role = new RoleDAO();
	public static RoleDAO getRole() {
		return role;
	}
}